import {
	useState,
	useImperativeHandle,
	forwardRef,
	useMemo,
	useEffect,
} from "react";
import {
	Modal,
	Form,
	Button,
	Table,
	Input,
	Select,
	Cascader,
	DatePicker,
	Pagination,
} from "antd";
import CommonSearchSelect from "./CommonSearchSelect";
import { getObjectFinalValue } from "@src/tools/commonTool";
declare const theFilterTypes: [
	"select",
	"input",
	"searchSelect",
	"cascader",
	"datePicker",
	"rangePicker"
];
const { RangePicker } = DatePicker;
declare type theFilterType = typeof theFilterTypes[number];
interface ForItemArray {
	filterType: theFilterType;
	field: string;
	label: string;
	placeholder?: string;
}
interface preQueryParamProps {
	fromField?: string;
	field: string;
	value: any;
}
interface CommonFilterTableModalProps {
	zIndex?: number;
	title: string;
	columns: any[];
	queryFunc: Function;
	filterList?: Array<ForItemArray[]>;
	showCheckBox?: boolean;
	rowKey?: string;
	tableButtons?: any[];
	preQueryParam?: Array<preQueryParamProps>;
}

function CommonFilterTableModal(props: CommonFilterTableModalProps, ref: any) {
	const [form] = Form.useForm();
	const {
		zIndex,
		title,
		columns = [],
		queryFunc = () => {},
		filterList = [],
		showCheckBox = false,
		rowKey,
		tableButtons = [],
		preQueryParam = [],
	} = props;
	const [showModal, setShowModal] = useState(false);
	const [dataSource, setDataSource] = useState([]);
	const [total, setTotal] = useState(0);
	const [current, setCurrent] = useState(1);
	const [selectedRowKeys, setSelectedRowKeys] = useState([] as any[]);
	const [preParam, setPreParam] = useState({});
	const [loading, setLoading] = useState(false);

	useImperativeHandle(ref, () => {
		return { openModal, selectedRowKeys, queryTableData };
	});
	useEffect(() => {
		if (!preParam || JSON.stringify(preParam) === "{}") {
			return;
		}
		queryTableData(current);
		// eslint-disable-next-line
	}, [current, preParam]);
	const openModal = (record: any) => {
		let obj: any = {};
		if (!!preQueryParam.length) {
			for (let i of preQueryParam) {
				if (!i.value) {
					if (!!i.fromField) {
						obj[i.field] = record[i.fromField];
					} else {
						obj[i.field] = record[i.field];
					}
				} else {
					obj[i.field] = i.value;
				}
			}
		}
		setCurrent(1);
		setPreParam(obj);
		setShowModal(true);
	};
	const closeModal = () => {
		setPreParam({});
		setLoading(false);
		setShowModal(false);
	};
	const queryTableData = (pageNum: number) => {
		let param = form.getFieldsValue();
		if (current !== 1 && pageNum === 1) {
			setCurrent(1);
			return;
		}
		param = {
			...param,
			...preParam,
			pageNum,
			pageSize: 5,
		};
		setLoading(true);
		queryFunc(param)
			.then((res: any) => {
				setTotal(getObjectFinalValue(res, "data.total") || "0");
				setDataSource(getObjectFinalValue(res, "data.data") || []);
				setLoading(false);
			})
			.catch(() => {
				setLoading(false);
			});
	};
	const resetFilter = () => {
		form.resetFields();
	};
	const changeSelectRows = (val: any) => {
		setSelectedRowKeys(val);
	};
	const rowSelection: any = {
		selectedRowKeys,
		onChange: changeSelectRows,
		fixed: "left",
	};
	const formItems = useMemo(() => {
		if (!filterList.length) {
			return null;
		}
		return filterList.map((item: any) => {
			let {
				filterType,
				field,
				label = "获取失败",
				placeholder,
				mode = undefined,
				allowClear = false,
				options,
				width,
				fieldNames,
				showSearch = false,
				fatherNode = true,
				searchFunc,
				style = {},
				labelInValue = false,
				preSearchParam,
			} = item;
			if (filterType === "searchSelect") {
				return (
					<Form.Item
						className="form-item"
						label={label}
						name={field}
						key={field}
						style={{ width: `${width}px` }}
					>
						<CommonSearchSelect
							labelInValue={labelInValue}
							mode={mode}
							SearchFunc={searchFunc}
							style={style}
							fieldNames={fieldNames}
							placeholder={placeholder}
							preSearchParam={preSearchParam}
						/>
					</Form.Item>
				);
			}
			if (filterType === "input") {
				return (
					<Form.Item
						className="form-item"
						label={label}
						name={field}
						key={field}
						style={{ width: `${width}px` }}
						getValueFromEvent={(e) => {
							return e.target.value.trim();
						}}
					>
						<Input
							allowClear={allowClear}
							placeholder={placeholder || "请填写"}
						/>
					</Form.Item>
				);
			}
			if (filterType === "select") {
				return (
					<Form.Item
						className="form-item"
						label={label}
						name={field}
						key={field}
						style={{ width: `${width}px` }}
					>
						<Select
							showSearch={showSearch}
							mode={mode}
							options={options}
							placeholder={placeholder || "请选择"}
							optionFilterProp="label"
							allowClear
						></Select>
					</Form.Item>
				);
			}
			if (filterType === "cascader") {
				return (
					<Form.Item
						className="form-item"
						label={label}
						name={field}
						key={field}
						style={{ width: `${width}px` }}
					>
						<Cascader
							options={options}
							changeOnSelect={fatherNode}
							fieldNames={fieldNames}
							expandTrigger="hover"
							placeholder={placeholder || "请选择"}
						/>
					</Form.Item>
				);
			}
			if (filterType === "datePicker") {
				return (
					<Form.Item
						className="form-item"
						label={label}
						name={field}
						key={field}
						style={{ width: `${width}px` }}
					>
						<DatePicker style={{ width: "100%" }} />
					</Form.Item>
				);
			}
			if (filterType === "rangePicker") {
				return (
					<Form.Item
						className="form-item range-picker"
						label={label}
						name={field}
						key={field}
						style={{ width: `${width}px` }}
					>
						<RangePicker style={{ width: "100%" }} />
					</Form.Item>
				);
			}
			return null;
		});
	}, [filterList]);
	const showtableButtons = useMemo(() => {
		if (!tableButtons.length) {
			return null;
		}
		return tableButtons.map((item, index: number) => {
			return (
				<Button
					className="table-button"
					key={index}
					type={item.type}
					onClick={() => {
						item.method();
					}}
				>
					{item.label}
				</Button>
			);
		});
	}, [tableButtons]);

	return (
		<Modal
			destroyOnClose
			zIndex={zIndex}
			title={title}
			visible={showModal}
			onCancel={closeModal}
			width={800}
			footer={null}
			centered
			className="common-filter-table-modal"
		>
			<Form form={form} layout="inline" className="filter-bar">
				{formItems}
				<div className="filter-buttons">
					<Button
						type="primary"
						onClick={() => {
							queryTableData(1);
						}}
					>
						查询
					</Button>
					<Button
						onClick={resetFilter}
						style={{ marginLeft: "10px" }}
					>
						重置
					</Button>
				</div>
			</Form>

			<Table
				bordered
				loading={loading}
				scroll={{ x: "100%" }}
				pagination={false}
				rowKey={rowKey}
				columns={columns}
				dataSource={dataSource}
				rowSelection={showCheckBox ? rowSelection : undefined}
			/>
			<div className="pagination-box">
				<div>{showtableButtons}</div>
				<Pagination
					total={total}
					current={current}
					showQuickJumper
					size="small"
					pageSize={5}
					showSizeChanger={false}
					hideOnSinglePage
					showTotal={(total) => `共${total}条数据`}
					onChange={(val) => {
						setCurrent(val);
					}}
				/>
			</div>
		</Modal>
	);
}

export default forwardRef(CommonFilterTableModal);
